<template>
  <div class="ai-claim-verification-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header-container">
      <el-page-header @back="handleBack" content="核赔信息管理" class="page-header" />
    </div>

    <!-- 查询表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" ref="searchFormRef">
        <el-form-item label="报案号" prop="reportNo">
          <el-input v-model="searchForm.reportNo" placeholder="请输入报案号" clearable style="width: 200px;"
            @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item label="核赔号" prop="verificationId">
          <el-input v-model="searchForm.verificationId" placeholder="请输入核赔号" clearable style="width: 200px;"
            @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item label="核赔状态" prop="verificationStatus">
          <el-select v-model="searchForm.verificationStatus" placeholder="请选择核赔状态" clearable style="width: 200px;">
            <el-option label="待核赔" value="0" />
            <el-option label="核赔通过" value="1" />
            <el-option label="核赔拒绝" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="searchLoading">
            <el-icon>
              <Search />
            </el-icon>查询
          </el-button>
          <el-button @click="resetForm">
            <el-icon>
              <Refresh />
            </el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格和分页 -->
    <el-card class="table-card">
      <div class="table-operations" v-if="tableData.length > 0">
        <span>共 <strong>{{ pagination.total }}</strong> 条记录</span>
      </div>

      <el-table :data="tableData" border stripe v-loading="tableLoading" element-loading-text="加载中..."
        style="width: 100%;" empty-text="暂无数据">
        <!-- <el-table-column type="index" label="序号" align="center" width="80" /> -->
        <el-table-column prop="reportNo" label="报案号" align="center" min-width="160" />
        <el-table-column prop="verificationId" label="核赔号" align="center" min-width="160" />
        <el-table-column prop="policyId" label="保单号" align="center" min-width="120" />
        <el-table-column prop="verificationStatus" label="核赔状态" align="center" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.verificationStatus === 1 ? 'success' :
              scope.row.verificationStatus === 2 ? 'danger' : 'warning'">
              {{ scope.row.verificationStatus === 1 ? '核赔通过' :
                scope.row.verificationStatus === 2 ? '核赔拒绝' : '待核赔' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="finalPayAmount" label="最终赔付金额" align="center" min-width="120"
          :formatter="formatCurrency" />
        <el-table-column prop="verificationTime" label="核赔时间" align="center" min-width="160" :formatter="formatDate" />
        <el-table-column label="操作" align="center" min-width="140">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleView(scope.row.verificationId)"
              :loading="operationLoading.view === scope.row.verificationId">
              <el-icon>
                <Search />
              </el-icon>查看
            </el-button>

            <!-- 删除按钮优化 -->
            <el-tooltip :content="getDeleteTooltip(scope.row)" placement="top"
              v-if="scope.row.verificationStatus !== 0">
              <el-button size="small" type="danger" disabled icon="Delete" class="delete-button" />
            </el-tooltip>

            <el-button v-else size="small" type="danger" @click="handleDelete(scope.row)"
              :loading="operationLoading.delete === scope.row.verificationId" icon="Delete" class="delete-button" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="pagination.total > 0">
        <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" :disabled="tableLoading" />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="核赔详情" :width="dialogWidth" :before-close="handleDialogClose"
      :close-on-click-modal="false">
      <!-- 详情内容保持不变 -->
      <el-descriptions column="1" border v-if="detailData" class="detail-descriptions" v-loading="detailLoading"
        element-loading-text="加载详情中...">
        <el-descriptions-item label="报案号">{{ detailData.reportNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="核赔号">{{ detailData.verificationId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="核算ID">{{ detailData.calculationId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="立案ID">{{ detailData.registrationId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="保单号">{{ detailData.policyId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="被保人ID">{{ detailData.insuredId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="核赔人ID">{{ detailData.verifierId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="核赔状态">
          <el-tag :type="detailData.verificationStatus === 1 ? 'success' :
            detailData.verificationStatus === 2 ? 'danger' : 'warning'">
            {{ detailData.verificationStatus === 1 ? '核赔通过' :
              detailData.verificationStatus === 2 ? '核赔拒绝' : '待核赔' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最终赔付金额">{{ formatCurrencyValue(detailData.finalPayAmount) }}</el-descriptions-item>
        <el-descriptions-item label="核赔意见">{{ detailData.verificationOpinion || '-' }}</el-descriptions-item>
        <el-descriptions-item label="核赔时间">{{ formatDateValue(detailData.verificationTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox, ElNotification, ElTooltip } from 'element-plus';
import { Search, Refresh, Delete } from '@element-plus/icons-vue';
import hxxp from '@/utils/hxxp';

// 搜索表单数据
const searchForm = reactive({
  reportNo: '',
  verificationId: '',
  verificationStatus: null
});

// 表单引用
const searchFormRef = ref(null);

// 表格数据
const tableData = ref([]);
const tableLoading = ref(false);
const searchLoading = ref(false);

// 操作加载状态
const operationLoading = reactive({
  view: null,
  delete: null
});

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 详情对话框
const detailDialogVisible = ref(false);
const detailData = ref(null);
const detailLoading = ref(false);
const dialogWidth = ref('700px');

// 页面加载时获取数据
onMounted(() => {
  fetchData();
});

// 监听分页参数变化
watch(
  () => [pagination.pageNum, pagination.pageSize],
  () => {
    fetchData();
  }
);

// 获取数据列表
const fetchData = async () => {
  try {
    tableLoading.value = true;

    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      reportNo: searchForm.reportNo || undefined,
      verificationId: searchForm.verificationId || undefined,
      verificationStatus: searchForm.verificationStatus !== null ? searchForm.verificationStatus : undefined
    };

    const response = await hxxp.get('/aiClaimVerification/all', { params });

    if (response.code === 100200) {
      tableData.value = response.data.list || [];
      pagination.total = response.data.total || 0;
      pagination.pageNum = response.data.pageNum || 1;
      pagination.pageSize = response.data.pageSize || 10;
    } else {
      ElMessage.error(response.msg || '获取数据失败');
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    tableData.value = [];
    pagination.total = 0;
    ElMessage.error('获取数据失败，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

// 获取删除按钮提示信息
const getDeleteTooltip = (row) => {
  if (row.verificationStatus === 1) {
    return '核赔通过的记录不允许删除';
  } else if (row.verificationStatus === 2) {
    return '核赔拒绝的记录不允许删除';
  }
  return '';
};

// 删除功能（优化版）
const handleDelete = async (row) => {
  try {
    // 1. 业务状态二次校验
    if (row.verificationStatus !== 0) {
      ElMessage.warning(getDeleteTooltip(row));
      return;
    }

    // 2. 详细的确认对话框
    const confirmResult = await ElMessageBox.confirm(
      `<div style="padding: 10px 0;">
        <p>您确定要删除以下核赔记录吗？</p>
        <div style="margin: 15px 0; padding: 10px; background: #f5f5f5; border-radius: 4px;">
          <p><strong>核赔号：</strong>${row.verificationId}</p>
          <p><strong>报案号：</strong>${row.reportNo}</p>
          <p><strong>保单号：</strong>${row.policyId || '-'}</p>
        </div>
        <p style="color: #ff4d4f; font-size: 13px;">⚠️ 注意：删除后数据将不可恢复，请谨慎操作！</p>
      </div>`,
      '确认删除',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        center: true
      }
    );

    if (confirmResult !== 'confirm') {
      return;
    }

    // 3. 执行删除操作
    operationLoading.delete = row.verificationId;

    const response = await hxxp.delete(`/aiClaimVerification/${row.verificationId}`);

    if (response.code === 100200) {
      ElNotification({
        title: '删除成功',
        message: `核赔号 ${row.verificationId} 已成功删除`,
        type: 'success',
        duration: 3000
      });
      fetchData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    // 忽略取消操作的错误
    if (error.name !== 'Error' && error.message !== 'cancel') {
      console.error('删除操作失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  } finally {
    operationLoading.delete = null;
  }
};

// 查看详情
const handleView = async (verificationId) => {
  try {
    operationLoading.view = verificationId;
    detailLoading.value = true;

    const response = await hxxp.get(`/aiClaimVerification/${verificationId}`);

    if (response.code === 100200) {
      detailData.value = response.data;
      detailDialogVisible.value = true;
    } else {
      ElMessage.error(response.msg || '获取详情失败');
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败，请稍后重试');
  } finally {
    operationLoading.view = null;
    detailLoading.value = false;
  }
};

// 搜索、重置、分页等其他方法保持不变
const handleSearch = () => {
  pagination.pageNum = 1;
  fetchData();
};

const resetForm = () => {
  if (searchFormRef.value) {
    searchFormRef.value.resetFields();
  }
  searchForm.reportNo = '';
  searchForm.verificationId = '';
  searchForm.verificationStatus = null;

  pagination.pageNum = 1;
  fetchData();
};

const handleSizeChange = (val) => {
  pagination.pageSize = val;
};

const handleCurrentChange = (val) => {
  pagination.pageNum = val;
};

const handleBack = () => {
  history.back();
};

const handleDialogClose = () => {
  detailDialogVisible.value = false;
};

const formatDate = (row, column, cellValue) => {
  const dateString = cellValue || row[column.property];
  if (!dateString) return '-';

  // 处理时间戳或日期字符串
  let date;
  if (typeof dateString === 'number') {
    // 如果是时间戳
    date = new Date(dateString);
  } else {
    // 如果是日期字符串
    date = new Date(dateString);
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return '-';
  }

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

const formatCurrency = (row, column, cellValue) => {
  const amount = cellValue !== undefined ? cellValue : row[column.property];
  if (amount === undefined || amount === null || amount === '') return '-';

  const numAmount = Number(amount);
  if (isNaN(numAmount)) return '-';

  return '¥' + numAmount.toFixed(2);
};

// 用于详情对话框的格式化函数（直接传值）
const formatCurrencyValue = (amount) => {
  if (amount === undefined || amount === null || amount === '') return '-';
  const numAmount = Number(amount);
  if (isNaN(numAmount)) return '-';
  return '¥' + numAmount.toFixed(2);
};

const formatDateValue = (dateString) => {
  if (!dateString) return '-';

  // 处理时间戳或日期字符串
  let date;
  if (typeof dateString === 'number') {
    // 如果是时间戳
    date = new Date(dateString);
  } else {
    // 如果是日期字符串
    date = new Date(dateString);
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return '-';
  }

  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};
</script>

<style scoped>
.ai-claim-verification-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 其他样式保持不变 */

/* 删除按钮样式优化 */
.delete-button {
  margin-left: 5px;
}

/* 禁用状态的删除按钮样式 */
:deep(.el-button--danger.is-disabled) {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 确认对话框内容样式 */
:deep(.el-message-box__content) {
  font-size: 14px;
  line-height: 1.6;
}
</style>
